package org.erepublik.company.controllers;

import java.util.Arrays;

import org.erepublik.company.CountryData;
import org.erepublik.company.comparators.CountryDataComparatorByName;
import org.erepublik.company.searchCriteria.CurrencySearchCriteria;
import org.erepublik.company.service.JSONCountryDataProvider;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

@Controller
@RequestMapping("/currencyPricesHistory.html")
public class CurrencyPriceController extends AbstractController  {

    @Autowired // autumatycznie wstrzykiwany obiekt
    private JSONCountryDataProvider dataService;
    
    @RequestMapping(method = RequestMethod.GET)
    public String showForm(ModelMap model) {
        fillModelMap(model);
        CountryData[] countryData = dataService.getAllCountryData();
        Arrays.sort(countryData, new CountryDataComparatorByName());
        model.addAttribute("countryData", countryData);
        model.addAttribute("updateTime", dataService.getMinutesSinceUpdate());
        model.addAttribute("currencySearchCriteria", new CurrencySearchCriteria());
        return "currencyPricesHistory";
    }
    
    @RequestMapping(method = RequestMethod.POST)
    public String showList(ModelMap model, @ModelAttribute("currencySearchCriteria") CurrencySearchCriteria criteria) {
        fillModelMap(model);
        CountryData[] countryData = dataService.getAllCountryData();
        Arrays.sort(countryData, criteria.getSortCriteria().getComparator() ) ;
        
        model.addAttribute("countryData", countryData);
        model.addAttribute("updateTime", dataService.getMinutesSinceUpdate());
        model.addAttribute("currencySearchCriteria", criteria);
        return "currencyPricesHistory";
    }
    
    
}
